<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket测试页面</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 30px;
            margin-bottom: 20px;
        }
        h1 {
            color: #2c3e50;
            margin-bottom: 20px;
        }
        .status {
            padding: 10px 20px;
            border-radius: 4px;
            margin-bottom: 20px;
            font-weight: bold;
        }
        .status.disconnected {
            background-color: #e74c3c;
            color: white;
        }
        .status.connected {
            background-color: #2ecc71;
            color: white;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        .buttons {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        button {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            background-color: #3498db;
            color: white;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #2980b9;
        }
        button:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
        }
        .message-container {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            background-color: #f9f9f9;
        }
        .message {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 4px;
            background-color: white;
            border-left: 3px solid #3498db;
            word-wrap: break-word;
        }
        .message.error {
            border-left-color: #e74c3c;
            background-color: #fee;
        }
        .message.info {
            border-left-color: #f39c12;
            background-color: #fff8e1;
        }
        pre {
            margin: 0;
            font-family: 'Courier New', Courier, monospace;
            white-space: pre-wrap;
        }
        .subscriptions {
            margin-top: 20px;
            padding: 15px;
            background-color: #ecf0f1;
            border-radius: 4px;
        }
        .subscription-item {
            margin-right: 10px;
            padding: 5px 10px;
            background-color: #3498db;
            color: white;
            border-radius: 4px;
            display: inline-block;
            margin-bottom: 5px;
        }
        .unsubscribe-btn {
            background: none;
            color: white;
            border: none;
            cursor: pointer;
            font-size: 14px;
            padding: 0 5px;
            margin-left: 5px;
        }
        .examples {
            margin-top: 20px;
        }
        .example-btn {
            margin-right: 10px;
            margin-bottom: 10px;
            background-color: #95a5a6;
        }
        .example-btn:hover {
            background-color: #7f8c8d;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket连接和订阅测试</h1>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div class="form-group">
            <label for="serverUrl">WebSocket服务器地址:</label>
            <input type="text" id="serverUrl" value="ws://localhost:8080/ws" placeholder="输入WebSocket服务器地址">
        </div>
        
        <div class="buttons">
            <button id="connectBtn" onclick="connect()">连接</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
        </div>
        
        <div class="form-group">
            <label for="channel">订阅频道:</label>
            <input type="text" id="channel" placeholder="输入要订阅的频道名称">
        </div>
        
        <div class="buttons">
            <button id="subscribeBtn" onclick="subscribe()" disabled>订阅</button>
            <button id="unsubscribeBtn" onclick="unsubscribe()" disabled>取消订阅</button>
        </div>
        
        <div class="examples">
            <p>常用频道示例:</p>
            <button class="example-btn" onclick="setExampleChannel('kline_BTCUSDT_1m')">BTC/USDT 1分钟K线</button>
            <button class="example-btn" onclick="setExampleChannel('kline_ETHUSDT_1m')">ETH/USDT 1分钟K线</button>
            <button class="example-btn" onclick="setExampleChannel('depth_BTCUSDT')">BTC/USDT 深度</button>
            <button class="example-btn" onclick="setExampleChannel('trade_BTCUSDT')">BTC/USDT 交易</button>
        </div>
        
        <div class="subscriptions">
            <h3>已订阅频道:</h3>
            <div id="subscriptionList"></div>
        </div>
    </div>
    
    <div class="container">
        <h2>接收到的消息</h2>
        <div id="messageContainer" class="message-container"></div>
    </div>

    <script>
        let socket = null;
        let subscriptions = new Set();
        
        function connect() {
            const serverUrl = document.getElementById('serverUrl').value;
            
            if (!serverUrl) {
                appendMessage('请输入WebSocket服务器地址', 'error');
                return;
            }
            
            try {
                socket = new WebSocket(serverUrl);
                
                socket.onopen = function(event) {
                    updateStatus(true);
                    appendMessage('WebSocket连接已建立', 'info');
                };
                
                socket.onmessage = function(event) {
                    console.log('接收到WebSocket消息:', event.data);
                    try {
                        // 尝试解析JSON消息
                        const data = JSON.parse(event.data);
                        console.log('解析后的消息:', data);
                        appendMessage(`接收到消息: ${JSON.stringify(data, null, 2)}`);
                    } catch (e) {
                        console.error('消息解析错误:', e);
                        // 如果不是JSON格式，直接显示
                        appendMessage(`接收到非JSON消息: ${event.data}`);
                    }
                };
                
                socket.onclose = function(event) {
                    updateStatus(false);
                    appendMessage(`WebSocket连接已关闭 (代码: ${event.code})`, 'info');
                };
                
                socket.onerror = function(error) {
                    appendMessage(`WebSocket错误: ${error}`, 'error');
                };
            } catch (e) {
                appendMessage(`连接失败: ${e}`, 'error');
            }
        }
        
        function disconnect() {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.close();
            }
        }
        
        function subscribe() {
            const channel = document.getElementById('channel').value.trim();
            
            if (!channel) {
                appendMessage('请输入频道名称', 'error');
                return;
            }
            
            if (!socket || socket.readyState !== WebSocket.OPEN) {
                appendMessage('WebSocket未连接', 'error');
                return;
            }
            
            if (subscriptions.has(channel)) {
                appendMessage(`已经订阅了频道: ${channel}`, 'info');
                return;
            }
            
            try {
                const subscribeMsg = JSON.stringify({
                    type: 'subscribe',
                    channel: channel
                });
                
                socket.send(subscribeMsg);
                subscriptions.add(channel);
                updateSubscriptionList();
                appendMessage(`已订阅频道: ${channel}`, 'info');
            } catch (e) {
                appendMessage(`订阅失败: ${e}`, 'error');
            }
        }
        
        function unsubscribe() {
            const channel = document.getElementById('channel').value.trim();
            
            if (!channel) {
                appendMessage('请输入频道名称', 'error');
                return;
            }
            
            if (!socket || socket.readyState !== WebSocket.OPEN) {
                appendMessage('WebSocket未连接', 'error');
                return;
            }
            
            if (!subscriptions.has(channel)) {
                appendMessage(`未订阅频道: ${channel}`, 'info');
                return;
            }
            
            try {
                const unsubscribeMsg = JSON.stringify({
                    type: 'unsubscribe',
                    channel: channel
                });
                
                socket.send(unsubscribeMsg);
                subscriptions.delete(channel);
                updateSubscriptionList();
                appendMessage(`已取消订阅频道: ${channel}`, 'info');
            } catch (e) {
                appendMessage(`取消订阅失败: ${e}`, 'error');
            }
        }
        
        function updateStatus(isConnected) {
            const statusElement = document.getElementById('status');
            const connectBtn = document.getElementById('connectBtn');
            const disconnectBtn = document.getElementById('disconnectBtn');
            const subscribeBtn = document.getElementById('subscribeBtn');
            const unsubscribeBtn = document.getElementById('unsubscribeBtn');
            
            if (isConnected) {
                statusElement.className = 'status connected';
                statusElement.textContent = '已连接';
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
                subscribeBtn.disabled = false;
                unsubscribeBtn.disabled = false;
            } else {
                statusElement.className = 'status disconnected';
                statusElement.textContent = '未连接';
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                subscribeBtn.disabled = true;
                unsubscribeBtn.disabled = true;
                subscriptions.clear();
                updateSubscriptionList();
            }
        }
        
        function appendMessage(message, type = 'normal') {
            const messageContainer = document.getElementById('messageContainer');
            const messageElement = document.createElement('div');
            messageElement.className = 'message ' + type;
            
            const timestamp = new Date().toLocaleTimeString();
            messageElement.innerHTML = `<strong>[${timestamp}]</strong><pre>${message}</pre>`;
            
            messageContainer.appendChild(messageElement);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
        
        function updateSubscriptionList() {
            const subscriptionList = document.getElementById('subscriptionList');
            subscriptionList.innerHTML = '';
            
            subscriptions.forEach(channel => {
                const item = document.createElement('span');
                item.className = 'subscription-item';
                item.textContent = channel;
                
                const unsubscribeBtn = document.createElement('button');
                unsubscribeBtn.className = 'unsubscribe-btn';
                unsubscribeBtn.textContent = '×';
                unsubscribeBtn.onclick = function() {
                    document.getElementById('channel').value = channel;
                    unsubscribe();
                };
                
                item.appendChild(unsubscribeBtn);
                subscriptionList.appendChild(item);
            });
        }
        
        function setExampleChannel(channel) {
            document.getElementById('channel').value = channel;
        }
        
        // 页面关闭时断开连接
        window.addEventListener('beforeunload', function() {
            disconnect();
        });
    </script>
</body>
</html>